<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.userId" clearable size="mini" class="filter-item" style="width: 200px;"
                placeholder="请输入用户ID"/>
      <el-input v-model="listQuery.orderSn" clearable size="mini" class="filter-item" style="width: 200px;"
                placeholder="请输入订单编号"/>
      <el-input v-model="listQuery.fetchCode" clearable size="mini" class="filter-item" style="width: 200px;"
                placeholder="请输入提货码"/>
      <el-select v-model="listQuery.orderStatusArray" multiple size="mini" style="width: 200px" class="filter-item"
                 placeholder="请选择订单状态">
        <el-option v-for="(key, value) in statusMap" :key="key" :label="key" :value="value"/>
      </el-select>
      <el-select v-model="listQuery.brandId" size="mini" style="width: 200px" class="filter-item" clearable
                 placeholder="请选择商户">
        <el-option
          v-for="item in brandIdArray"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
        <!--<el-option v-for="(key, value) in settlementFlagMap" :key="key" :label="key" :value="value"/>-->
      </el-select>
      <el-select v-model="listQuery.settlementFlag" size="mini" style="width: 200px" class="filter-item" clearable
                 placeholder="请选择结算状态">
        <el-option
          v-for="item in settlementFlagArray"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
        <!--<el-option v-for="(key, value) in settlementFlagMap" :key="key" :label="key" :value="value"/>-->
      </el-select>
      <el-button v-permission="['GET /admin/order/verifyList']" size="mini" class="filter-item" type="primary"
                 icon="el-icon-search" @click="handleFilter">查找
      </el-button>
      <el-button :loading="downloadLoading" size="mini" class="filter-item" type="warning" icon="el-icon-download"
                 @click="handleDownload">导出
      </el-button>
      <br/>
      <el-date-picker v-model="listQuery.startTime" type="datetime" placeholder="选择起始时间" style="width: 200px;"/>
      <el-date-picker v-model="listQuery.endTime" type="datetime" placeholder="选择结束时间" style="width: 200px;"/>
      <el-input v-model="listQuery.sumAmount" size="mini" style="width: 150px" readonly value="" class="filter-item"
                type="primary"
                placeholder="结算总金额"/>
      <el-button v-permission="['POST /admin/order/finishOrder']" size="mini" class="filter-item" type="primary"
                 icon="el-icon-search" @click="handleShip">批量结算
      </el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" size="small" element-loading-text="正在查询中。。。"
              @selection-change="selectionRowsChange" border fit highlight-current-row>
      <el-table-column align="center" min-width="100" type="selection" sortable/>
      <el-table-column align="center" min-width="100" label="订单ID" prop="id"/>
      <el-table-column align="center" min-width="100" label="订单编号" prop="orderSn" sortable/>

      <el-table-column align="center" min-width="80px" label="用户ID" prop="userId"/>

      <el-table-column align="center" min-width="80px" label="订单状态" prop="orderStatus">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.orderStatus | orderStatusFilter }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" min-width="90px" label="订单金额" prop="orderPrice"/>

      <el-table-column align="center" min-width="90px" label="支付金额" prop="actualPrice"/>

      <el-table-column align="center" min-width="120px" label="支付时间" prop="payTime"/>

      <!--<el-table-column align="center" min-width="110px" label="物流单号" prop="shipSn"/>

      <el-table-column align="center" min-width="80px" label="物流渠道" prop="shipChannel"/>
-->
      <el-table-column align="center" min-width="120px" label="商户名" prop="brandName"/>
      <el-table-column align="center" min-width="120px" label="结算时间" prop="settlementTime"/>
      <el-table-column align="center" min-width="100px" label="结算状态" prop="settlementFlag">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.settlementFlag == 2 ? '已结算' : '未结算' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" min-width="120px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!--<el-button v-permission="['GET /admin/order/verifyDetail']" type="primary" size="mini" @click="handleDetail(scope.row)">详情</el-button>-->
          <el-button v-permission="['POST /admin/order/finishOrder']" v-if="scope.row.hasSettlement" type="warning"
                     size="mini" @click="handleSettlement(scope.row.id)">结算
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 发货对话框 -->
    <el-dialog :visible.sync="shipDialogVisible" title="结算页">
      <el-form ref="shipForm" :model="shipForm">

        <el-table v-loading="listLoading" :data="brandLists" size="small" element-loading-text="正在查询中。。。">
          <el-table-column align="center" min-width="90px" label="商户名" prop="brandName"/>
          <el-table-column align="center" min-width="90px" label="订单数" prop="sum"/>
          <el-table-column align="center" min-width="120px" label="支付金额" prop="amount"/>
        </el-table>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="shipDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmShip">结算</el-button>
        <el-button :loading="downloadLoading" size="mini" class="filter-item" type="warning" icon="el-icon-download"
                   @click="brandListDownload">导出
        </el-button>
      </div>
    </el-dialog>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"/>

  </div>
</template>

<style>
.box-card {
  margin: 30px 0px;
}

.box-card .el-form-item {
  margin-bottom: 5px;
}
</style>

<script>
import {finishOrder, verifyBrandList, verifyDetail, verifyList} from '@/api/business/order'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import checkPermission from '@/utils/permission' // 权限判断函数

const statusMap = {
  101: '未付款',
  102: '用户取消',
  103: '系统取消',
  201: '已付款',
  204: '团购中',
  202: '申请退款',
  206: '等待退款',
  203: '已退款',
  301: '已发货',
  401: '用户收货',
  402: '系统收货'
}
const settlementFlagArray = [
  {label: '未结算', value: 1},
  {label: '已结算', value: 2}
]

export default {
  name: 'VerifyOrder',
  components: {Pagination},
  filters: {
    orderStatusFilter(status) {
      return statusMap[status]
    }
  },
  data() {
    return {
      list: undefined,
      total: 0,
      listLoading: true,
      shipChannelList: [],
      listQuery: {
        page: 1,
        limit: 20,
        id: undefined,
        name: undefined,
        orderStatusArray: [],
        settlementFlag: undefined,
        startTime: undefined,
        endTime: undefined,
        brandId: undefined,
        sumAmount: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      brandLists: [],
      rows: [],
      statusMap,
      settlementFlagArray,
      brandIdArray: [],
      orderDialogVisible: false,
      orderDetail: {
        order: {},
        user: {},
        orderGoods: []
      },
      shipForm: {
        orderId: undefined,
        shipChannel: undefined,
        shipSn: undefined
      },
      shipDialogVisible: false,
      refundForm: {
        orderId: undefined,
        refundMoney: undefined
      },
      orderRefundDetail: {
        order: {},
        user: {},
        refundOrderList: []
      },
      refundDialogVisible: false,
      downloadLoading: false
    }
  },
  created() {
    this.listQuery.settlementFlag = this.settlementFlagArray[0].value
    this.listQuery.orderStatusArray = ['401', '402']
    this.getVerifyBrandList()
    this.getList()
  },
  methods: {
    checkPermission,
    selectionRowsChange(val) {
      let sum = 0
      val.forEach(item => {
        sum += item.actualPrice
      })
      this.listQuery.sumAmount = parseFloat(sum).toFixed(2)
      this.rows = val
    },
    getList() {
      this.listLoading = true
      verifyList(this.listQuery).then(response => {
        this.list = response.data.data.items
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    getVerifyBrandList() {
      verifyBrandList().then(response => {
        this.brandIdArray = response.data.data.brandList
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.listQuery.page = 1
      this.getList()
    },
    commonBatchVerity(data) {
      var orderIdList = '';
      data.forEach(item => {
        orderIdList = orderIdList + item.id + ','
      })
      if (orderIdList.length > 0) {
        this.$confirm('您确定要结算吗？').then(() => {
          finishOrder(orderIdList).then(response => {
            console.info(response)
            this.$notify.success({
              title: '成功',
              message: '操作成功'
            })
            this.shipDialogVisible = false
            this.getList()
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
        }).catch(() => {
          console.log('cancel')
        })
      }
    },
    handleBatchVerity() {
      this.commonBatchVerity(this.rows)
    },
    handleSettlement(id) {
      var data = [{'id': id}]
      this.commonBatchVerity(data)
    },
    handleDetail(row) {
      verifyDetail(row.id).then(response => {
        this.orderDetail = response.data.data
      })
      this.orderDialogVisible = true
    },

    handleShip() {
      if (this.rows == undefined || this.rows == null || this.rows.length <= 0) {
        this.$notify.error({
          message: '结算必须有选中订单！'
        })
        return
      } else {
        var sets = new Set()
        var bool = true
        this.rows.forEach((item) => {
          sets.add(item.brandId)
          if (item.settlementFlag == 2) {
            bool = false
          }
        })
        if (!bool) {
          this.$notify.error({
            message: '选中订单中有重复结算订单，请再次确认！'
          })
          return
        }
        sets.forEach((item) => {
          let entity = {"brandId": item}
          let sum = 0
          let amount = 0
          this.rows.forEach((obj) => {
            if (item == obj.brandId) {
              entity.brandName = obj.brandName
              sum += 1
              amount += obj.actualPrice
            }
          })
          entity.sum = sum
          entity.amount = amount
          this.brandLists.push(entity)
        })
        console.info(sets)
        console.info(this.brandLists)

        this.shipDialogVisible = true
        this.$nextTick(() => {
          this.$refs['shipForm'].clearValidate()
        })
      }
    },
    confirmShip() {
      this.handleBatchVerity()
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['订单ID', '订单编号', '用户ID', '订单状态', '订单金额', '支付金额', '支付时间', '商户名', '结算时间', '结算状态1未结算2已结算']
        const filterVal = ['id', 'orderSn', 'userId', 'orderStatus', 'orderPrice', 'actualPrice', 'payTime', 'brandName', 'settlementTime', 'settlementFlag']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, addDate() +'结算信息')
        this.downloadLoading = false
      })
    },

    brandListDownload() {

      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['商户名', '订单数', '支付金额']
        const filterVal = ['brandName', 'sum', 'amount']
        excel.export_json_to_excel2(tHeader, this.brandLists, filterVal, addDate() + '商户结算汇总')
        this.downloadLoading = false
      })
    }
  }
}

function addDate() {
  var nowDate = new Date();
  let date = {
    year: nowDate.getFullYear(),
    month: nowDate.getMonth() + 1,
    date: nowDate.getDate(),
  }
  console.log(date);
  return date.year + '-' + +date.month + '-' + +date.date;
}
</script>
